import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/basic/base_info.dart';
import 'package:sptapp/moudle/event_bus.dart';
import 'package:sptapp/widget/common_widget.dart';
import 'package:system_settings/system_settings.dart';
import '../../config/const.dart';
import '../../moudle/location/location_tool.dart';
import '../../moudle/message.dart';

class DeviceNetPage extends StatefulWidget {
  const DeviceNetPage({super.key});

  @override
  State<DeviceNetPage> createState() => _DeviceNetPageState();
}

class _DeviceNetPageState extends State<DeviceNetPage> {

  TextEditingController _wifiController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  bool isPwd = true;
  String wifi = '';
  String pwd = '';
  String res = '';

  final _locationService = LocationService();
  final _geocodingService = GeocodingService();

  String address = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _showAlert();
    wifi = LocalBaseInfo.getWifiName() ?? '';
    _wifiController.text = wifi;
    _getCurrentLocation();
  }
  _connect()async{
    FocusScope.of(context).requestFocus(FocusNode());
    showLoading();
    HttpClient httpClient = HttpClient();
    bool isSuccess = false;
    try{
      httpClient.connectionTimeout = Duration(seconds: 10); //
      HttpClientRequest request = await httpClient.postUrl(Uri.parse(
          'http://192.168.19.1/index.html'
      ));
      final encode = utf8.encode('stassid=$wifi&stapwd=$pwd');
      request.headers.set(
        'Content-Type',
        'application/x-www-form-urlencoded',
        preserveHeaderCase: true,
      );
      request.headers.set(
        'Content-Length',
        encode.length.toString(),
        preserveHeaderCase: true,
      );
      request.add(encode);
      final response = await request.close();
      String reply = await response.transform(utf8.decoder).join();
      if(reply.isNotEmpty && !reply.contains('<span>Disconnected</span>')){
        isSuccess = true;
        eventBus.fire(DeviceInfoChange());
      }
    }catch(e){
      print('e==== $e');
    }
    finally {
      httpClient.close();
      hideLoading();
      _showSuccessAlert();
      // if(isSuccess){
      //   Navigator.of(context).popUntil(ModalRoute.withName("index"));
      //   _showSuccessAlert();
      // }else{
      //   showToast('Password entered incorrectly Please Re Enter');
      // }
  }
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  _showAlert() {
    SmartDialog.show(builder: (ctx){
      return Container(
        width: 600.w,
        decoration: BoxDecoration(
          color: Color(0xff1E1D20),
          borderRadius: BorderRadius.circular(16.w)
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              child: Stack(
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 32.w,horizontal: 48.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('Device Network Settings'.tr,style: TextStyle(
                            color: Colors.white,
                            fontSize: 32.sp,
                          fontWeight: FontWeight.w400
                        ),)
                      ],
                    ),
                  ),
                  Positioned(
                      child: GestureDetector(
                    onTap: (){
                      SmartDialog.dismiss();
                    },
                    child: Container(
                      child: Image.asset('assets/common/common_close_w.png',width: 48.w,),
                    ),
                  ),
                    right: 24.w,
                    top: 24.w,
                  )
                ],
              ),
            ),
            Container(height: 1.w,color: Color.fromRGBO(255, 255, 255, 0.2),),
            SizedBox(height: 46.w,),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              child: Column(
                children: [
                  Container(
                    child: Text('Please go to the system settings to connect to your device\'s WiFi.'.tr,
                    style: TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 1),
                      fontSize: 32.sp,
                      fontWeight: FontWeight.w500
                    ),textAlign: TextAlign.center,),
                    alignment: Alignment.center,
                  ),
                ],
              ),
            ),
            SizedBox(height: 64.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                _goWifiSetting();
              },
              child: Container(
                alignment: Alignment.center,
                width: 500.w,
                height: 108.w,
                decoration: BoxDecoration(
                  color: Color(0xff3C55F8),
                  borderRadius: BorderRadius.circular(8.w)
                ),
              child: Text('Go to Wifi setting'.tr,style: TextStyle(
                color: Colors.white,
                fontSize: 32.sp,
                fontWeight: FontWeight.w600
              ),),
            ),
            ),
            SizedBox(height: 32.w,)
          ],
        ),
      );
    },alignment: Alignment.center);
  }

  Future<void> _getCurrentLocation() async {
    try {
      final position = await _locationService.getCurrentLocation();
      if(position!=null){
         address = await _geocodingService.getAddressFromLatLng(position!.latitude, position!.longitude);
      }
    } catch (e) {
    }
  }

  _showSuccessAlert() {
    SmartDialog.show(builder: (ctx){
      return Container(
        width: 600.w,
        decoration: BoxDecoration(
            color: Color(0xff1E1D20),
            borderRadius: BorderRadius.circular(16.w)
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              child: Stack(
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 32.w,horizontal: 48.w),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text('Prompt Message'.tr,style: TextStyle(
                            color: Colors.white,
                            fontSize: 32.sp
                        ),)
                      ],
                    ),
                  ),
                  Positioned(
                    child: GestureDetector(
                      onTap: (){
                        SmartDialog.dismiss();
                      },
                      child: Container(
                        child: Image.asset('assets/common/common_close_w.png',width: 48.w,),
                      ),
                    ),
                    right: 24.w,
                    top: 24.w,
                  )
                ],
              ),
            ),
            Container(height: 1.w,color: Color.fromRGBO(255, 255, 255, 0.2),),
            SizedBox(height: 46.w,),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              child: Column(
                children: [
                  Container(
                    child: Text('Check the device to see if the connection is successful.\nOnce it\'s done, switch back to your home WI-FI.'.tr,
                      style: TextStyle(
                          color: Color.fromRGBO(255, 255, 255, 1),
                          fontSize: 32.sp,
                          fontWeight: FontWeight.w600
                      ),textAlign: TextAlign.center,),
                  ),
                ],
              ),
            ),
            SizedBox(height: 64.w,),
            GestureDetector(
              onTap: (){
                SmartDialog.dismiss();
                _goWifiSetting();
              },
              child: Container(
                alignment: Alignment.center,
                width: 500.w,
                height: 108.w,
                decoration: BoxDecoration(
                    color: Color(0xff3C55F8),
                    borderRadius: BorderRadius.circular(8.w)
                ),
                child: Text('Go to Wifi setting'.tr,style: TextStyle(
                    color: Colors.white,
                    fontSize: 32.sp,
                    fontWeight: FontWeight.w600
                ),),
              ),
            ),
            SizedBox(height: 32.w,)
          ],
        ),
      );
    },alignment: Alignment.center);
  }

  _goWifiSetting()async{
    SystemSettings.wifi();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      appBar: myAppBar(context, device_net_page_title.tr,actions: [
        GestureDetector(
          onTap: (){
            Navigator.of(context).pushNamed('MinDeviceNetInfoPage');
          },
          child: Container(
            padding: EdgeInsets.only(right: 40.w),
            child: Image.asset('assets/common/device_net_info.png',width: 48.w,),
          ),
        )
      ]),
      body: GestureDetector(
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          alignment: Alignment.topCenter,
          padding: EdgeInsets.symmetric(horizontal: 40.w),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                //logo 图片
                // SizedBox(height: ScreenUtil().statusBarHeight + 40.w,),
                SizedBox(height: 40.w,),
                //邮箱输入框
                Container(
                  width: 690.w,
                  height: 108.w,
                  padding: EdgeInsets.symmetric(horizontal: 30.w),
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.white,width: 1.w),
                      borderRadius: BorderRadius.circular(20.w)
                  ),
                  child:  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(child: TextField(
                        //控制器
                        textInputAction: TextInputAction.done,
                        controller: _wifiController,
                        maxLines: 1,
                        //是否自动更正
                        autocorrect: true,
                        //是否自动对焦
                        autofocus: false,
                        style: inputStyle,
                        inputFormatters: [

                        ],
                        decoration: InputDecoration(
                          contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                          hintText: device_net_page_item_wifi_hittText.tr,
                          hintStyle: inputHitStyle,
                          counterText: "",
                          border: OutlineInputBorder(
                              borderSide: BorderSide.none),
                        ),
                        onChanged: (val){
                          setState(() {
                            wifi = val.trim();
                          });
                        },
                      )),
                      SizedBox(width: 20.w,),
                      Visibility(visible: wifi!=null&&wifi!.isNotEmpty,
                        child: GestureDetector(
                          onTap: (){
                            setState(() {
                              _wifiController.text = '';
                              wifi = '';
                            });
                          },
                          child: Container(
                            child: inputImg,
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(height: 32.w,),
                //密码输入框
                Container(
                  width: 690.w,
                  height: 108.w,
                  padding: EdgeInsets.symmetric(horizontal: 30.w),
                  decoration: BoxDecoration(
                      border: Border.all(color: Colors.white,width: 1.w),
                      borderRadius: BorderRadius.circular(20.w)
                  ),
                  child:  Row(
                    children: [
                      Expanded(child: TextField(
                        //控制器
                        controller: _pwdController,
                        // maxLength: 11,
                        maxLines: 1,
                        //是否自动更正
                        autocorrect: true,
                        //是否自动对焦
                        autofocus: false,
                        obscureText: isPwd,
                        style: inputStyle,
                        decoration:  InputDecoration(
                          //                hintText: "请输入用户名",
                          contentPadding: EdgeInsets.zero,
                          hintText: device_net_page_item_pwd_hittText.tr,
                          hintStyle: inputHitStyle,
                          counterText: "",
                          border: const OutlineInputBorder(
                              borderSide: BorderSide.none),
                        ),
                        onChanged: (val) {
                          setState(() {
                            pwd = val.trim();
                          });
                        },
                      )),
                      SizedBox(width: 20.w,),
                      Visibility(visible: true,
                        child: GestureDetector(
                          onTap: (){
                            setState(() {
                             isPwd = !isPwd;
                            });
                          },
                          child: Container(
                            child: Image.asset(isPwd?'assets/common/input_hide.png':'assets/common/input_show.png',width: 48.w,),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 32.w,),
               Container(
                 alignment: Alignment.centerLeft,
                 child: Text('Please enter your home Wi-Fi account and password.'.tr,style: TextStyle(
                   color: Colors.white,
                   fontSize: 24.sp,
                 ),),
               ),
                SizedBox(height: 40.w,),

                GestureDetector(
                  onTap: ()async{

                    if(wifi.isEmpty || pwd.isEmpty){
                      return;
                    }
                    _connect();
                  },
                  child: Container(
                    width: 654.w,
                    height: 108.w,
                    decoration: BoxDecoration(
                        color: wifi.isNotEmpty && pwd.isNotEmpty ? themeColor:themeDisableColor,
                        borderRadius: BorderRadius.circular(8.w)
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(device_net_page_item_sure.tr,style: TextStyle(
                            color: Colors.white,
                            fontSize: 28.sp,
                            fontWeight: FontWeight.w600
                        ),)
                      ],
                    ),
                  ),
                ),
                SizedBox(height: 32.w,),
                GestureDetector(
                  onTap: ()async{
                    _goWifiSetting();
                  },
                  child: Container(
                    width: 654.w,
                    height: 108.w,
                    decoration: BoxDecoration(
                        color: themeColor,
                        borderRadius: BorderRadius.circular(8.w)
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text('Go to Wifi setting'.tr,style: TextStyle(
                            color: Colors.white,
                            fontSize: 28.sp,
                            fontWeight: FontWeight.w600
                        ),)
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

}
